#encoding=utf-8
import sys
import socket
import MySQLdb
import time
import gevent
from gevent import socket

class Db(object):
	"""docstring for Db"""
	def __init__(self, arg):
		try:
			super(Db, self).__init__()
			self.arg = arg
			self.db = MySQLdb.connect(self.arg["host"], self.arg["username"], self.arg["password"], self.arg["db"])
		except Exception, e:
			self.db.close()
			raise e
		finally:
			pass

	def insert(self, data):
		# sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('%s', '%s', '%d', '%c', '%d' )" % ('Mac', 'Mohan', 20, 'M', 2000)
		sql = "show tables"
		try:
			cursor = self.db.cursor()
			cursor.execute(sql)
			self.db.commit()
			# self.db.close()
		except:
			self.db.rollback()
			self.db.close()
		finally:
			pass

	def update(self):
		pass


def server(port, db_config):
	bind_address = ('0.0.0.0', port)
	s = socket.socket()
	s.bind(bind_address)
	s.listen(500)
	db = Db(db_config)
	while True:
		cli, addr = s.accept()
		gevent.spawn(handle_request, cli, addr, gevent.sleep, db)

def handle_request(s, addr, sleep, db):
	try:
		s.send('欢迎来到Server %s'%str(addr))
		data = s.recv(2048)
		information = decode(data)
		# result = data_analyse(information)
		db.insert("hallo")
		s.shutdown(socket.SHUT_WR)
		print ('%sbe killed'%str(addr))
	except Exception, ex:
		print ex
	finally:
		s.close()

# para:data msg = 'speed|133|oil_temperature|22|water_temperature|45|oil_pressure|32|others|1012210291|'
# return  {"speed":133, "oil_temperature":22, "water_temperature":45, "oil_pressure":32,"others":1011} 
def data_analyse(data):
	result = data.split('|')
	context = {}
	n = 0
	for i in range(len(result)//2):
		key = result[n]
		value = result[n+1]
		n = n+2
		context[key] = value
	return context

# para:data 0x7e 0x30 7d 0x02 0x08 0x7d 0x01 0x55 0x7e  msg 0x30 0x7e 0x08 0x7d 0x55
def decode(data):
	data_list = data.split(' ')
	if data_list[0]=='0x7e' and data_list[-1]=='0x7e':
		data_list.pop(0) and data_list.pop(-1)
		for index, temp_data in enumerate(data_list):
			if temp_data == '0x7d':
				if data_list[index+1] == '0x02':
					data_list.pop(index+1)
					data_list[index] = '0x7e'
				elif data_list[index+1] == '0x01':
					data_list.pop(index+1)
					data_list[index] = '0x7d'
				else:
					raise 'encode error'
			# data_list[index] = int(data_list[index], 16)
			# data_list[index] = chr(data_list[index])
	import pdb
	pdb.set_trace()
	information = data_list
	return information

if __name__ == '__main__':
	db_config = {"host":"localhost", "username":"root", "password":"123456", "db":"shiptest2"}
	server(9200, db_config)
